package com.dykj.fireFighting.server.base.bigdata.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dykj.fireFighting.api.base.bigdata.device.entity.Device;
import com.dykj.fireFighting.api.base.bigdata.device.service.IDeviceService;
import com.dykj.fireFighting.api.base.bigdata.device.vo.DeviceVo;
import com.dykj.fireFighting.api.base.devHisResult.vo.ResultVo;
import com.dykj.fireFighting.api.base.enterprise.entity.Enterprise;
import com.dykj.fireFighting.api.base.enterprise.service.IEnterpriseService;
import com.dykj.fireFighting.common.core.service.impl.BaseServiceImpl;
import com.dykj.fireFighting.common.starter.redis.service.RedisService;
import com.dykj.fireFighting.server.base.bigdata.mapper.DeviceMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 *
 */
@Slf4j
@DubboService
@Transactional(rollbackFor = Exception.class)
public class DeviceServiceImpl extends BaseServiceImpl<DeviceMapper, Device> implements IDeviceService {

    @Autowired
    private IEnterpriseService iEnterpriseService;
    @Autowired
    private RedisService redisService;
    @Override
    public List<DeviceVo> deviceStatistics(HashMap<String, Object> params) {
        return this.baseMapper.deviceStatistics(params);
    }

    @Override
    public List<DeviceVo> queryFaultStatistical(String unitId) {
        Map<String, Object> params = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(unitId)) {
            List<Enterprise> enterpriseList = iEnterpriseService.queryUnitSelect(unitId);
            if (CollectionUtil.isNotEmpty(enterpriseList)) {
                params.put("enterpriseList", enterpriseList);
            }
        }
        List<String> bjztList = new ArrayList<>();
        bjztList.add("08");
        params.put("bjztList", bjztList);
        return this.baseMapper.queryFaultStatistical(params);
    }


    @Override
    public List<DeviceVo> selectByUnit(String s) {
        return this.baseMapper.selectByUnit(s);
    }

    @Override
    public List<DeviceVo> selectByCenter(List<String> ids) {
        return this.baseMapper.selectByCenter(ids);
    }

    @Override
    public int countTotal(String s) {
        QueryWrapper<Device> wrapper = new QueryWrapper<>();
        wrapper.eq("is_del", 0)
                .eq("unit_id", s);
        return this.baseMapper.selectCount(wrapper).intValue();
    }

    @Override
    public int countFault(String s) {
        QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del", 0)
                .eq("unit_id", s)
                .eq("is_gz", 0);
        return this.baseMapper.selectCount(queryWrapper).intValue();
    }

    @Override
    public int countCenterTotal(List<String> ids) {
        QueryWrapper<Device> wrapper = new QueryWrapper<>();
        wrapper.eq("is_del", 0)
                .in("unit_id", ids);
        return this.baseMapper.selectCount(wrapper).intValue();
    }

    @Override
    public int countCenterFault(List<String> ids) {
        QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del", 0)
                .eq("is_gz", 0)
                .in("unit_id", ids);
        return this.baseMapper.selectCount(queryWrapper).intValue();
    }

    @Override
    public List<Device> getSelect(String id, String type) {
        QueryWrapper<Device> wrapper = new QueryWrapper<>();
        wrapper.eq("unit_id", id)
                .eq("type", type);
        return this.baseMapper.selectList(wrapper);
    }

    @Override
    public int countFaultByTime(String s, String beginTime, String endTime) {
        QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del", 0)
                .eq("unit_id", s)
                .eq("is_gz", 0)
                .between("update_time", beginTime, endTime);
        return this.baseMapper.selectCount(queryWrapper).intValue();
    }

    @Override
    public Map<String, Double> faultEffectiveRecoveryRate(List<String> ids,String month) {
        Map<String, Double> value = new HashMap<>();
        //计算当月有效复核率
        int recoveryNum = this.baseMapper.faultRecoveryNum(ids,month);//恢复总数
        if (recoveryNum == 0) {
            //判断本月是否存在故障
            int now = this.baseMapper.getFaultNum(ids,month);
            if (now > 0) {
                value.put(month, 0.0);
            } else {
                value.put(month, 100.0);
            }

        } else {
            int effectiveRecoveryNum = this.baseMapper.faultEffectiveRecoveryNum(ids,month);//有效恢复数
            BigDecimal b = new BigDecimal((double) effectiveRecoveryNum / (double) recoveryNum);//计算模拟量值
            double now = b.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;//取三位小数
            value.put(month, now);
        }
        /*计算上月有效复核率*/
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM");
        String lastMonth=null;
        try {
            Date sourceDate = sdf.parse(month);
            Calendar cal = Calendar.getInstance();
            cal.setTime(sourceDate);
            cal.add(Calendar.MONTH, -1);
            lastMonth=sdf.format(cal.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int recoveryNumLast = this.baseMapper.faultRecoveryNum(ids,lastMonth);
        if (recoveryNumLast == 0) {
            //判断上月是否存在故障
            int last = this.baseMapper.getFaultNum(ids,lastMonth);
            if (last > 0) {
                value.put(lastMonth, 0.0);
            } else {
                value.put(lastMonth, 100.0);
            }

        } else {
            int effectiveRecoveryNumLast = this.baseMapper.faultEffectiveRecoveryNum(ids,lastMonth);
            BigDecimal bLast = new BigDecimal((double) effectiveRecoveryNumLast / (double) recoveryNumLast);//计算模拟量值
            double last = bLast.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;//取三位小数
            value.put(lastMonth, last);
        }
        return value;
    }

    @Override
    public Device getByRelationId(String relationId) {
        QueryWrapper<Device> wrapper = new QueryWrapper<>();
        wrapper.eq("relation_id", relationId)
                .eq("is_del", 0);
        return this.baseMapper.selectOne(wrapper);
    }

    @Override
    public Device getDeviceByRelationId(String relationId) {
        return this.baseMapper.getDeviceByRelationId(relationId);
    }

    /**
     * 改维保端调用社会端  复制到base， 728183 728184 不知道是啥去社会端此方法找原作者
     */
    @Override
    public Object getDevicedetails(String relationId) {
            /*QueryWrapper<Device> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("relation_id",relationId);
        Device device = deviceMapper.selectOne(queryWrapper);*/
        Device device = this.baseMapper.getDeviceByRelationId(relationId);
        if("728183".equals(device.getDevSysType())){
            Device device1 = JSON.parseObject((String) redisService.get(relationId), Device.class);
            if(device1!=null){
                device.setStatus(device1.getStatus());
                device.setCalculationValue(device1.getCalculationValue());
            }
            return device;
        }else if("728184".equals(device.getDevSysType())){
            return this.baseMapper.getDeviceElectricalDetails(relationId);
        }

        return device;
    }

    @Override
    public int getAllUnitByCount(List<String> ids, String begin, String end, Integer o) {
        return this.baseMapper.getAllUnitByCount(ids,begin,end,o);
    }

    @Override
    public List<ResultVo> getDayByDate(String unitId, String beginTime, String endTime) {
        return this.baseMapper.getDayByDate(unitId,beginTime,endTime);
    }

    @Override
    public List<ResultVo> getMonthByDate(String unitId, String beginTime, String endTime) {
        return this.baseMapper.getMonthByDate(unitId,beginTime,endTime);
    }

    @Override
    public List<ResultVo> getQuarterByDate(String unitId, String beginTime, String endTime) {
        return this.baseMapper.getQuarterByDate(unitId,beginTime,endTime);
    }

    @Override
    public List<ResultVo> getYearByDate(String unitId, String beginTime, String endTime) {
        return this.baseMapper.getYearByDate(unitId,beginTime,endTime);
    }

    @Override
    public List<ResultVo> getAllDay(List<String> ids, String beginTime, String endTime) {
        return this.baseMapper.getAllDay(ids,beginTime,endTime);
    }

    @Override
    public List<ResultVo> getAllMonth(List<String> ids, String beginTime, String endTime) {
        return this.baseMapper.getAllMonth(ids,beginTime,endTime);
    }

    @Override
    public List<ResultVo> getAllQuarter(List<String> ids, String beginTime, String endTime) {
        return this.baseMapper.getAllQuarter(ids,beginTime,endTime);
    }

    @Override
    public List<ResultVo> getAllYear(List<String> ids, String beginTime, String endTime) {
        return this.baseMapper.getAllYear(ids,beginTime,endTime);
    }

}
